import React, { useState, useEffect, useMemo, useRef } from 'react';
import { connect } from 'react-redux';
import { Button, Row, Col, Form, message } from 'antd';
import ComponentBase from '../form/ComponentBase';
import services from 'src/services/api';
import useVariableData from 'src/hook/useVariableData';
import useActionsData from 'src/hook/useActionsData';
import useOperatorData from 'src/hook/useOperatorData';
import { STRATEGY_TYPE, USAGE_SCOPE_LIMIT, VARIABLE_TYPE } from 'src/utils/constant';
import { randomKey } from 'src/utils/utils';
import usePrevious from 'src/hook/usePrevious';
import { cloneDeep, debounce } from 'lodash';
import Modal from 'src/components/Modal/index';
import Test from './test';
import StrategyConfig from './StrategyConfig';

/**
 * @method StrategyComponentAdd
 */

function StrategyComponentAdd(props) {
  const [appId, setAppId] = useState('');
  const [eventId, setEventId] = useState('');
  const [detail, setDetail] = useState({});
  const [mode, setMode] = useState();

  const [reloadKey, setReloadKey] = useState('a');
  const [changedVariableStr, setChangedVariableStr] = useState('');
  const variable = useVariableData({
    limitType: [
      VARIABLE_TYPE._FIELD,
      VARIABLE_TYPE._FEATURE,
      VARIABLE_TYPE._MODEL,
      VARIABLE_TYPE._NAMELIST,
      VARIABLE_TYPE._THIRD_FEATURE,
      VARIABLE_TYPE._STRATEGY,
      VARIABLE_TYPE._RISK_LEVEL,
      VARIABLE_TYPE._LITERAL,
    ],
    appId,
    eventId,
    codes: props.codes,
    reloadKey,
  });
  const actions = props.isImportant ? props.actions || [] : useActionsData(USAGE_SCOPE_LIMIT._STRATEGY); //获取动作函数的列表
  const prevEventId = usePrevious(eventId);
  const prevAppId = usePrevious(appId);

  const operator = useOperatorData();

  const _strategyConfig = useRef(null); //策略配置组件

  useEffect(() => {
    if (props.actionType !== 'detail') {
      props.dispatch({ type: 'pageClose/waringAdd' });
    }
    return () => {
      if (props.actionType !== 'detail') {
        props.dispatch({ type: 'pageClose/waringReduce' });
      }
    };
  }, []);

  // appId或者event_id改变，则设置 changedVariableStr = appId+','+eventId, 需要清空规则
  useMemo(() => {
    // 都存在
    if (
      (prevEventId !== '' || prevEventId !== undefined) &&
      (eventId !== '' || eventId !== undefined) &&
      (prevAppId !== '' || prevAppId !== undefined) &&
      (appId !== '' || appId !== undefined)
    ) {
      //且被改变
      if (prevEventId !== eventId || prevAppId !== appId) {
        setChangedVariableStr(appId + ',' + eventId);
      }
    }
  }, [appId, eventId]);

  useEffect(() => {
    if (props.id) {
      getDetail(props.id, props.version);
    }
    if (props.record && props.record.strategy_id && !props.isAuditLog) {
      getDetail(props.record.strategy_id, props.record.version);
    }
    if (props.value && Object.keys(props.value).length > 0) {
      setDetailData(cloneDeep(props.value));
    }
  }, []);
  useEffect(() => {
    if (props.value && Object.keys(props.value).length > 0) {
      setDetailData(cloneDeep(props.value));
    }
  }, [props.value]);

  // 获取详情
  function getDetail(id, version) {
    const params = version ? { strategy_id: id, version } : { strategy_id: id };
    services.strategyComponent.queryOne(params).then((res) => {
      if (res.code === 0) {
        res.data.product_id = res.data.product_id || '';
        setDetailData(cloneDeep(res.data));
      } else {
        message.error(res.msg);
      }
    });
  }

  // 设置detail数据
  function setDetailData(data) {
    data.strategy_mode && setMode(data.strategy_mode);
    setDetail(data);

    // 如果是复制，则去掉rule_id
    if (props.actionType === 'copy') {
      data.strategy_config.mode &&
        data.strategy_config.mode.express_rules &&
        data.strategy_config.mode.express_rules.forEach((item) => {
          delete item.rule_id;
        });
    }
  }

  // 改变模式
  function changeModeHandel(mode) {
    setMode(mode);
  }

  function reloadVariable() {
    setReloadKey(randomKey());
  }

  // 返回
  function back() {
    props.history.push('/strategy/component');
  }

  // 提交
  function handleSubmit(e, type) {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        const params = {};
        params.app_id = values.app_id;
        params.event_id = values.event_id;
        params.product_id = values.product_id || '';
        params.name = values.name;
        params.code = values.code;
        params.remark = values.remark;
        params.strategy_mode = values.strategy_mode;
        params.strategy_type = STRATEGY_TYPE._COMMON; // 组件默认传1
        params.status = values.status;
        if (props.isAuditLog) params.is_audit_log = true; // 审核记录里重新编辑，后端不做比较
        // 组件配置
        _strategyConfig.current.getValue(values, (value, error) => {
          if (!error) {
            const isOverLap = sectionOverlap(value);
            if (!isOverLap) {
              return;
            }
            params.strategy_config = value;

            if (props.actionType === 'update' && !props.localSubmit) {
              params.strategy_id = props.isAuditLog ? props.record.strategy_id : props.id;
            }
            if (type === 'test') return handleTest(params);
            const action = props.actionType === 'copy' || props.actionType === 'add' ? 'add' : 'update';

            if (!props.localSubmit) {
              services.strategyComponent[action](params).then((res) => {
                if (res.code === 0) {
                  message.success(res.msg);
                  if (props.afterSubmit) {
                    props.afterSubmit();
                  } else {
                    props.closeModal && props.closeModal();
                    if (props.isAuditLog) return;
                    props.history.push('/strategy/component');
                  }
                } else {
                  message.error(res.msg);
                }
              });
            } else {
              props.usePolicy(params);
            }
          } else {
            return;
          }
        });
      }
    });
  }
  // 验证 风险权重、评分卡、权重区间，得分区间， 不可重叠
  function sectionOverlap(value) {
    const weightRules = (value.mode.risk_weight && value.mode.risk_weight.weight_range_rules) || []; // 权重区间
    const scoreRangeCode = (value.mode.score_card && value.mode.score_card.score_range_rules) || []; // 得分区间
    const scoreCalcCode = (value.mode.score_card && value.mode.score_card.score_calc_rules) || []; // 规则分享区间
    if (!reduceList(weightRules)) {
      message.warning('权重区间不可重叠');
      return false;
    }
    if (!reduceList(scoreRangeCode)) {
      message.warning('得分区间不可重叠');
      return false;
    }
    scoreCalcCode.forEach((item) => {
      item.cases.forEach((itm) => {
        if (itm.min > itm.max) {
          message.warning('分箱区间左值不能大于右值');
          throw '分箱区间左值不能大于右值';
        }
      });
      if (!reduceList(item.cases)) {
        message.warning('分箱区间不可重叠');
        throw '分箱区间不可重叠';
      }
    });
    return true;
  }
  function reduceList(data) {
    const newArr = data.map((item) => {
      return [item.min, item.max];
    });
    let isOvers = true;
    newArr.reduce((pre, cur, index) => {
      if (index) {
        if (OverlapFn(pre, cur) !== undefined) {
          isOvers = OverlapFn(pre, cur);
        }
        const newList = [...pre, ...cur];
        return [Math.min(...newList), Math.max(...newList)];
      } else {
        return cur;
      }
    }, []);
    return isOvers;
  }
  // 两两对比判断是区间重复
  function OverlapFn(oldList, newList) {
    let max = [oldList[0], newList[0]];
    let min = [oldList[1], newList[1]];
    if (Math.max(...max) < Math.min(...min)) {
      return false;
    }
  }
  // 组件测试
  const handleTest = (params) => {
    services.policy.test(params).then(({ code, data, msg }) => {
      if (!code) {
        Modal.open({
          title: '组件测试',
          width: '1000px',
          content: <Test value={data} actions={actions} variable={variable} using_variables={detail.using_variables} />,
          isOkBtn: false,
          maskClosable: false,
          cancel: () => {
            Modal.close();
          },
        });
      } else {
        message.error(msg);
      }
    });
  };
  return (
    <div className='stretegy-wp tantuer-form' id='intro-farm' style={{ position: 'relative' }}>
      <Form onSubmit={() => false} className='stretegy-wp-form'>
        <div className='tantuer-field-area'>
          <div className='form-title'>基本信息</div>

          <ComponentBase
            {...props}
            value={detail}
            actionType={props.actionType}
            localSubmit={props.localSubmit}
            changeModeHandel={changeModeHandel}
            onGetAppProductEventIds={({ appId, eventId }) => {
              setAppId(appId);
              setEventId(eventId);
            }}
          />
        </div>
        {eventId && mode && (
          <StrategyConfig
            {...props}
            key={eventId}
            mode={mode}
            variable={variable}
            actions={actions}
            using_variables={detail.using_variables}
            strategy_config={detail.strategy_config}
            appId={appId}
            eventId={eventId}
            reloadVariable={reloadVariable}
            changedVariableStr={changedVariableStr}
            is_exec_condition={props.form.getFieldValue('is_exec_condition')}
            createRef={_strategyConfig}
            operator={operator}
            disabled={props.actionType === 'detail'}
          />
        )}

        <Row type='flex' justify='start' className='form-submit-area'>
          <Col>
            {!props.isCompare && props.actionType !== 'detail' && (
              <Button style={{ marginRight: '15px' }} onClick={debounce((e) => handleSubmit(e, 'test'), 300)}>
                组件测试
              </Button>
            )}
            {props.actionType !== 'detail' && !props.changeMode && (
              <>
                {!props.localSubmit ? (
                  <>
                    <Button
                      type='primary'
                      onClick={handleSubmit}
                      data-intro='点击确认，流程编辑完毕，系统按照您设计的流程执行'
                      data-step='3'
                    >
                      确定
                    </Button>
                    <Button
                      style={{ marginLeft: '15px' }}
                      onClick={() => {
                        props.isAuditLog ? props.closeModal(true) : back();
                      }}
                    >
                      取消
                    </Button>
                  </>
                ) : (
                  <>
                    <Button
                      type='primary'
                      onClick={handleSubmit}
                      data-intro='点击确认，流程编辑完毕，系统按照您设计的流程执行'
                      data-step='3'
                    >
                      确定
                    </Button>
                    <Button style={{ marginLeft: '15px' }} onClick={() => props.closeModal()}>
                      取消
                    </Button>
                  </>
                )}
              </>
            )}
            {props.changeMode &&
              (props.actionType !== 'detail' ? (
                <>
                  <Button type='primary' onClick={handleSubmit}>
                    确定
                  </Button>
                  <Button className='marl10' onClick={props.cancelEdit}>
                    取消编辑
                  </Button>
                </>
              ) : (
                <>
                  <Button type='primary' onClick={props.startEdit}>
                    编辑
                  </Button>
                </>
              ))}
          </Col>
        </Row>
      </Form>
    </div>
  );
}
function mapStateToProps(state) {
  return {
    codes: {
      ...state.code,
    },
  };
}
export default connect(mapStateToProps)(Form.create()(StrategyComponentAdd));
